package service

import (
	"fmt"
	"gitee.com/jamon/espoir_go/common"
	"gitee.com/jamon/espoir_go/common/utils"
	"gitee.com/jamon/espoir_go/logger"
	"sync"
)

type Manager struct {
	requestPluginMap utils.Map[uint32, *ReqPluginInterface] // msgBaseID -> plugin
}

var (
	mgr  *Manager
	once sync.Once
)

func GetManager() *Manager {
	once.Do(func() {
		mgr = &Manager{
			requestPluginMap: ReqPluginsMap,
		}
	})
	return mgr
}

func (mgr *Manager) HandleRequest(req *common.MsgRequest, res *common.MsgResponse) (err error) {
	plugin, ok := mgr.requestPluginMap.Get(req.MsgId / common.DefaultInnerMsgIDs.LenRange)
	if !ok {
		logger.Error("HandleRequest: unknown msg id: ", logger.Kwargs{"msg_id": req.MsgId})
		return fmt.Errorf("unknownMsg|HandleRequest|id=%v", req.MsgId)
	}
	err = (*plugin).HandleMsg(req, res)
	return
}

func (mgr *Manager) GetRouteInfo(req *common.MsgRequest) (routeGroupID uint32, subAddress uint32, err error) {
	plugin, ok := mgr.requestPluginMap.Get(req.MsgId / common.DefaultInnerMsgIDs.LenRange)
	if !ok {
		logger.Error("GetRouteInfo: unknown msg id: ", logger.Kwargs{"msg_id": req.MsgId})
		return 0, 0, fmt.Errorf("unknownMsg|GetRouteInfo|id=%v", req.MsgId)
	}
	routeGroupID, subAddress, err = (*plugin).GetRouteInfo(req)
	return
}
